import 'dart:async';
import 'dart:convert';
import 'dart:typed_data';
import 'dart:io';

import 'package:ble_demo/ble/ble_action_type.dart';
import 'package:ble_demo/ble/ble_device.dart';
import 'package:ble_demo/ble/ble_plugin.dart';
import 'package:ble_demo/entity/smart_device.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:intl/intl.dart';
import 'package:path_provider/path_provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:ble_demo/http/index.dart';

/**
 * 设备列表
 */
class EcgDeviceDisplayData extends StatefulWidget {
  //智能设备
  SmartDevice smartDevice;

  EcgDeviceDisplayData(this.smartDevice);

  @override
  State<StatefulWidget> createState() => EcgDeviceDisplayDataState();
}

class EcgDeviceDisplayDataState extends State<EcgDeviceDisplayData>
    with WidgetsBindingObserver {
//显示结果
  String data = "0.0";
  DateTime _dateTime = DateTime.now();
  Timer _timer;
  var dataFormat = DateFormat("yyyy-MM-dd HH:mm:ss");
  String showTime = "";
  //设备是否可用
  bool isEnable = false;
  //设备本地存储器
  Future<SharedPreferences> _device_prefs = SharedPreferences.getInstance();

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    //计时器
    _timer = Timer.periodic(Duration(seconds: 1), (timer) {
      setState(() {
        _dateTime = DateTime.now();
        showTime = dataFormat.format(_dateTime);
      });
    });

    /// ble监听初始化
    BlePlugin.addListener(onBleListener);
    //再次进入扫描
    _hasDevicePrefs(widget.smartDevice.mac).then((hasDevice){
      if(hasDevice){
        //2s调用扫描
        Future.delayed(Duration(seconds: 2),(){
          BlePlugin.startHeartScan(mac: widget.smartDevice.mac);
        });
      }
    }
    );
  }
  Future<bool> _hasDevicePrefs(String mac) async {
    SharedPreferences preferences = await _device_prefs;
    return preferences.containsKey(mac);
  }


  /**
   *绑定用户
   */
  _bindDeviceByUserId(String mac) async {
    final SharedPreferences prefs = await _device_prefs;
    String userId = "123456";
    //todo
    //发送请求然后绑定到服务器
    int deviceType = 1;
    switch (widget.smartDevice.deviceType) {
      case SmartDeviceType.BODY_GUN:
        deviceType = 2;
        break;
      case SmartDeviceType.BODY_FAT:
        deviceType = 3;
        break;
    }
    DeviceHttp.checkBind({"sn": mac, "device_type": deviceType}).then((result) {
      if (result != null) {
        int resultCode = jsonDecode(result)["data"]["res"];
        if (resultCode == 0) {
          //设备未绑定
          DeviceHttp.bind({"sn": mac, "device_type": deviceType}).then((value) {
            if (value == 200) {
              prefs.setString(mac, userId);
            } else {
              EasyLoading.showError("设备绑定失败!");
            }
          });
        } else if (resultCode == 1) {
          //被自己绑定
          print("===设备被自己绑定===");
        } else if (resultCode == 2) {
          EasyLoading.showError("设备已经被别人绑定，请先解绑!");
        }
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: Color(0xffeeeeee),
        appBar: AppBar(
            centerTitle: true,
            actions: [
              FlatButton(
                  onPressed: () {},
                  child: Text(
                    "设备详情",
                    style: TextStyle(color: Colors.orangeAccent, fontSize: 18),
                  ))
            ],
            title: Text(
              "测量心率",
              style: TextStyle(color: Colors.black),
            )),
        body: _buildDisplayDataWidget(context, widget.smartDevice.deviceType));
  }

  /// 销毁
  @override
  dispose() {
    if (_timer != null) {
      _timer.cancel();
    }
    BlePlugin.removeListener(onBleListener);
    super.dispose();
  }

  //测量显示数据widget
  _buildDisplayDataWidget(
      BuildContext context, SmartDeviceType smartDeviceType) {
    return Padding(
        padding: const EdgeInsets.all(10),
        child: Center(
            child: Column(
                crossAxisAlignment: CrossAxisAlignment.center,
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
              isEnable
                  ? _buildShowData(context, smartDeviceType)
                  : _buildDefaultState(context, smartDeviceType),
              Text(
                "双手大拇指请握住心率仪两边接触区域",
                style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
              ),
              Padding(padding: const EdgeInsets.all(10), child: Text("测量心率"))
            ])));
  }

  //设备连接之前
  _buildDefaultState(BuildContext context, SmartDeviceType smartDeviceType) {
    return Image.asset("assets/images/img_ecg.png", fit: BoxFit.contain);
  }

  //连接成功显示数据
  _buildShowData(BuildContext context, SmartDeviceType smartDeviceType) {
    return Stack(
      alignment: Alignment.center,
      children: <Widget>[
        Image.asset("assets/images/img_ring_pul.png", fit: BoxFit.contain),
        Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Padding(
              padding: const EdgeInsets.all(10),
              child: Text("$showTime"),
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Text(
                  "$data",
                  style: TextStyle(fontWeight: FontWeight.bold, fontSize: 24),
                ),
                Padding(
                  padding: const EdgeInsets.only(left: 10),
                  child: Text("bpm"),
                )
              ],
            ),
            Padding(padding: const EdgeInsets.all(10), child: Text("平均心率")),
          ],
        )
      ],
    );
  }

  getFile(Uint8List srcFile) async {
    if (srcFile != null) {
      final tempDir = await getTemporaryDirectory();
      final file = await new File('${tempDir.path}/data.txt').create();
      file.writeAsBytesSync(srcFile);
      return file;
    }
  }

  onBleListener(type, params) {
    //android端监测完数据后返回到flutter页面显示
    print("type==$type,params=$params");
    if (type == BleActionType.ONHEARTECGDATADISPLAY) {
      String sn = jsonDecode(params)["deviceCode"];
      String ecgValue = jsonDecode(params)["ecgValue"];
      setState(() {
        isEnable = true;
        data = ecgValue;
      });

      String recordData = jsonDecode(params)["recordData"];
      //上传数据
      uploadRecordData(sn,base64Decode(recordData));

      //执行用户绑定
      _bindDeviceByUserId(widget.smartDevice.mac);
    }
  }
  

  void uploadRecordData(String sn,Uint8List recordData) async{
    print("开始上传文件=======设备码："+sn);
    //上传数据
    File file =await getFile(recordData);
    MultipartFile multipartFile = await MultipartFile.fromFile(file.path);
    DeviceHttp.uploadHeartRate({"sn":sn,"heart":multipartFile}).then((result){
        int code = jsonDecode(result)["code"];
        if(code == 200){
          print(jsonDecode(result)["message"]);
        }
        print("返回结果："+jsonDecode(result));
    });
  }
}
